import { Schema } from './schema';
import { reject } from 'promise';
import * as _ from 'lodash';
export class ValidatorService {
  private time: number;
  public validate(service: Function, schema: Schema, params: Object, schemaCheck?: Object): Promise<any> {
    const data = JSON.parse(JSON.stringify(params));
    if (schema.schema) {
      const error = {};
      const __validator = schemaCheck ? schemaCheck : schema.schema();
      const validForArr = (__validator, _data, error) => {
        _data.forEach((res, index) => {
          if (_.isArray(res) && _.isArray(__validator[index])) {
            error.push([]);
            validForArr(__validator[index], _data[index], error[index]);
          } else if (_.isObject(res) && _.isObject(__validator[0])) {
            error.push({});
            validForIn(__validator[0], _data[index], error[index], index);
          }
        });
      }
      const validForIn = (__validator, _data, error, index = null) => {
        for (const k in __validator) {
          if (_.isFunction(__validator[k])) {
            if (typeof _data[k] === 'undefined' || _data[k] === null || _data[k] === '') {
              _data[k] = '';
            }
            const v = __validator[k](data, _data[k], index, _data);
            if (v) {
              error[k] = v;
            }
          } else if (_.isArray(__validator[k])) {
            error[k] = [];
            validForArr(__validator[k], _data[k], error[k]);
          } else if (_.isObject(__validator[k])) {
            error[k] = {};
            if (!_data[k]) {
              _data[k] = {};
            }
            validForIn(__validator[k], _data[k], error[k]);
          }
        }
      }
      validForIn(__validator, data, error);
      let pass = true;
      const passFn = (err) => {
        for (const key in err) {
          if (_.isArray(err[key]) || _.isObject(err[key])) {
            passFn(err[key])
          } else {
            pass = false;
            break;
          }
        }
      }
      passFn(error);
      if (pass) {
        return service();
      } else {
        // 报错表单锚点
        this.time = setTimeout(() => {
          const formError: Element| null = document.querySelector('.form-error');
          if (formError) {
            formError.scrollIntoView();
          }
          clearTimeout(this.time);
        }, 300)
        return  reject({ err: error});
      }
    } else {
      return reject({ err: '缺少验证配置信息' });
    }
  };
}